package cn.telling.product.dao.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import cn.telling.common.util.TellingConstance;
import cn.telling.common.util.UserUtil;
import cn.telling.product.dao.IStoreProductDao;
import cn.telling.product.vo.LgStoreUpdate;
import cn.telling.product.vo.StoreProductVo;
import cn.telling.product.vo.SupplyArea0Vo;
import cn.telling.utils.AutoInjection;
import cn.telling.utils.BaseUtil;
import cn.telling.utils.StringHelperTools;

/**
 * 
 * @ClassName: StoreProductDaoImpl 
 * @Description: 产品库存数据服务接口的实现
 * @author 陈赟 
 * @date 2015年6月17日 上午9:33:05 
 *
 */
@Repository("storeProductDao")
public class StoreProductDaoImpl implements IStoreProductDao {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(StoreProductDaoImpl.class);
    
    @Autowired
    @Qualifier("film-template")
    private JdbcTemplate jdbcTemplate;
    
//    @Autowired
//    @Qualifier("film-template")
//    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public void insertStoreProduct(List<StoreProductVo> storeProductList) {
        String sql = "insert into store_product (id,PK_STORDOC,productid,quantity,allocatable) values(SEQ_STORE_PRODUCT.NEXTVAL,?,?,?,?)";
        List<Object[]> batchArgs = new ArrayList<Object[]>();
        for(StoreProductVo vo : storeProductList) {
            Object[] o = new Object[]{vo.getPk_stordoc(),vo.getProductid(),vo.getQuantity(),vo.getAllocatable()};
            batchArgs.add(o);
            LOGGER.debug("批量插入产品库存信息：" + BaseUtil.logSQL(sql, o));
        }
        jdbcTemplate.batchUpdate(sql, batchArgs);
    }

    @Override
    public int storeProductLog(StoreProductVo vo) {
        String sql = "insert into store_product_log (pk_stordoc,productid,quantity, allocatable,optype,optime,remarks,supplyid) values(?,?,?,?,?,sysdate,?,?)";
        Object[] args = new Object[]{vo.getPk_stordoc(),vo.getProductid(),vo.getQuantity(),vo.getAllocatable(),vo.getOpType(),vo.getRemarks(),vo.getSupplyid()};
        args = StringHelperTools.nullToString(args);
        LOGGER.debug("保存库存变动日志：" + BaseUtil.logSQL(sql, args));
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public void updateStoreProduct(String id, String allocatable) {
        String sql = "update store_product set allocatable = ? where id = ? ";
        Object args [] = new Object[]{allocatable,id};
        args = StringHelperTools.nullToString(args);
        
        LOGGER.debug("更新产品库存:" + BaseUtil.logSQL(sql,args));
        
        jdbcTemplate.update(sql,args);
    }

    @Override
    public StoreProductVo getStoreProductByAreaIdAndProductId(String areaId, String productId) {
        String sql = "select a.* from STORE_PRODUCT a LEFT JOIN relation_areastorage b on a.PK_STORDOC=b.PK_STORDOC and b.ISMAIN='4' INNER JOIN BI_STORE bs on bs.storecode=b.pk_stordoc and bs.storelevel='03' where b.AREAID=? and a.PRODUCTID=? ";
        Object args [] = new Object[]{areaId, productId};
        args = StringHelperTools.nullToString(args);
        
        LOGGER.debug("根据区域ID、产品ID获取库存信息：" + BaseUtil.logSQL(sql, args));
        List<StoreProductVo> storeList = jdbcTemplate.query(sql,args, new RowMapper<StoreProductVo>() {
            public StoreProductVo mapRow(ResultSet rs, int rowNum)throws SQLException {
                StoreProductVo vo = new StoreProductVo();
                AutoInjection.Rs2Vo(rs, vo, null);
                return vo;
            }
        });
        if(storeList != null && storeList.size() > 0) {
            return storeList.get(0);
        }
        return null;
    }

    @Override
    public int updateStoreProductBatch(List<SupplyArea0Vo> supplyArea0List, List<StoreProductVo> storeList, String source) {
        int updateNum = 0;
        if(supplyArea0List != null && supplyArea0List.size() > 0) {
            String sql = "";
            List<Object[]> batchArgs = new ArrayList<Object[]>();
            if(source.equals(TellingConstance.SOURCE_ORDER)) {
                sql = "update SUPPLY_AREA0 set OVERPLUSNUMBER=? where ID=?";
            } else if (source.equals(TellingConstance.SOURCE_ALLOCATE)) {
                sql = "update SUPPLY_AREA0 set OVERPLUSNUMBER=?, STOCKNUMBER=? where ID=?";
            }
            
            for(SupplyArea0Vo vo : supplyArea0List) {
                Object[] o = null;
                if(source.equals(TellingConstance.SOURCE_ORDER)) {
                    o = new Object[]{vo.getOverplusNumber(), vo.getId()};
                } else if (source.equals(TellingConstance.SOURCE_ALLOCATE)) {
                    o = new Object[]{vo.getOverplusNumber(), vo.getStockNumber(), vo.getId()};
                }
                batchArgs.add(o);
                LOGGER.debug("{}批量修改产品发布的库存：{}", new Object[]{source, BaseUtil.logSQL(sql, o)});
            }
            int[] num = jdbcTemplate.batchUpdate(sql, batchArgs);
            updateNum += num.length;
        }
        
        if(storeList != null && storeList.size() > 0) {
            String sql = "";
            List<Object[]> batchArgs = new ArrayList<Object[]>();
            if(source.equals(TellingConstance.SOURCE_ORDER)) {
                sql = "update STORE_PRODUCT set ALLOCATABLE=? where ID=?";
            } else if (source.equals(TellingConstance.SOURCE_ALLOCATE)) {
                sql = "update STORE_PRODUCT set ALLOCATABLE=?, QUANTITY=? where ID=?";
            }
            for(StoreProductVo vo : storeList) {
                Object[] o = null;
                if(source.equals(TellingConstance.SOURCE_ORDER)) {
                    o = new Object[]{vo.getAllocatable(), vo.getId()};
                } else if (source.equals(TellingConstance.SOURCE_ALLOCATE)) {
                    o = new Object[]{vo.getAllocatable(), vo.getQuantity(), vo.getId()};
                }
                batchArgs.add(o);
                LOGGER.debug("批量修改store_product的库存：" + BaseUtil.logSQL(sql, o));
            }
            int[] num = jdbcTemplate.batchUpdate(sql, batchArgs);
            updateNum += num.length;
        }
        return updateNum;
    }

    @Override
    public List<SupplyArea0Vo> getSupplyArea0ByPkStorDocAndProductIds(String pkStorDoc, String productIds) {
        String sql = "select a.id,a.supplyProductId,a.areaId,a.priceRetailOnline,a.stockNumber,a.overplusNumber,a.customId,a.saleType,b.productId from SUPPLY_AREA0 a INNER JOIN SHOP_PRODUCT b ON a.SUPPLYPRODUCTID=b.ID and b.PRODUCTID in (" + productIds + ") INNER JOIN SUPPLY c on b.SUPPLYID=c.ID and c.SUPPLY_TYPE=? where a.PK_STORDOC=? and a.SALETYPE=? and a.DEL_FLAG=?";
        Object[] args = new Object[]{UserUtil.TELLING_SUPPLY_17, pkStorDoc, TellingConstance.SALETYPE2, TellingConstance.DEL_FLAG_1};
        args = StringHelperTools.nullToString(args);
        
        LOGGER.debug("根据仓库编码、产品ID获取天联华建发布的非定向记录：" + BaseUtil.logSQL(sql, args));
        
        List<SupplyArea0Vo> supplyArea0List = jdbcTemplate.query(sql, args, new RowMapper<SupplyArea0Vo>(){

            @Override
            public SupplyArea0Vo mapRow(ResultSet rs, int rowNum) throws SQLException {
                SupplyArea0Vo vo = new SupplyArea0Vo();
                AutoInjection.Rs2Vo(rs, vo, null);
                return vo;
            }
            
        });
        return supplyArea0List;
    }

    @Override
    public List<StoreProductVo> getStoreProductByPkStorDocAndProductIds(String pkStorDoc, String productIds) {
        String sql = "select a.* from STORE_PRODUCT a where a.PK_STORDOC=? and a.PRODUCTID in (" + productIds + ") ";

        Object args [] = new Object[]{pkStorDoc};
        args = StringHelperTools.nullToString(args);
        
        /*List<Long> ids = new ArrayList<Long>();
        ids.add(1L);
        ids.add(2L);
        ids.add(3L);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pkStorDoc", pkStorDoc);
        paramMap.put("productIds", ids);
        
        List<StoreProductVo> storeList = jdbcTemplate.query(sql, paramMap, new RowMapper<StoreProductVo>() {
            public StoreProductVo mapRow(ResultSet rs, int rowNum)throws SQLException {
                StoreProductVo vo = new StoreProductVo();
                AutoInjection.Rs2Vo(rs, vo, null);
                return vo;
            }
        });*/
        LOGGER.debug("根据仓库编码、产品ID获取库存信息：" + BaseUtil.logSQL(sql, args));
        List<StoreProductVo> storeList = jdbcTemplate.query(sql,args, new RowMapper<StoreProductVo>() {
            public StoreProductVo mapRow(ResultSet rs, int rowNum)throws SQLException {
                StoreProductVo vo = new StoreProductVo();
                AutoInjection.Rs2Vo(rs, vo, null);
                return vo;
            }
        });
        return storeList;
    }

    @Override
    public int insertLgStoreUpdate(List<LgStoreUpdate> lgStoreUpdateList) {
        String sql = "insert into LG_STORE_UPDATE (UPDATE_SOURCE,UPDATE_TARGET,SOURCE_CODE,TARGET_CODE,PRODUCT_ID,UPDATE_TYPE,UPDATE_COUNT,BEFORE_UPDATE_STOCK,BEFORE_UPDATE_AVAILABLE,UPDATE_TIME) values(?,?,?,?,?,?,?,?,?,sysdate)";
        List<Object[]> batchArgs = new ArrayList<Object[]>();
        for(LgStoreUpdate vo : lgStoreUpdateList) {
            Object[] o = new Object[]{
                    vo.getUpdate_source(),
                    vo.getUpdate_target(),
                    vo.getSource_code(),
                    vo.getTarget_code(),
                    vo.getProduct_id(),
                    vo.getUpdate_type(),
                    vo.getUpdate_count(),
                    vo.getBefore_update_stock(),
                    vo.getBefore_update_available()
                    };
            batchArgs.add(o);
            LOGGER.debug("批量插入库存日志信息：" + BaseUtil.logSQL(sql, o));
        }
        int[] num = jdbcTemplate.batchUpdate(sql, batchArgs);
        return num.length;
    }

}
